<?php
/**
 * Introduction: 购物车  product_cart
 */

namespace Common\Model;


use Think\Model;

class ProductCartModel extends Model
{
    //定义数据库连接信息
    protected $connection;

    //定义表名
    protected $tableName = 'product_cart';

    /**
     * 初始化
     */
    public function _initialize()
    {

        $this->connection = C('Databaese');

    }

    /**
     * 获取一条数据
     */
    public function getRow($member_id,$shop_id,$skuid,$warehouseType,$supplierId){
        $where = "1=1 and product_id=$skuid and status>0";

        if ($member_id > 0) {
            $where .= " and member_id = $member_id";
        }
        if($shop_id){
            $where .= " and ms_id=$shop_id";
        }

        if ($supplierId !== null) {
            $where .= " and supplier_id = $supplierId";
        }
        if ($warehouseType !== null) {
            $where .= " and warehouse_type=$warehouseType";
        }
        $record = $this->where($where)->field("num")->find();

        if (!empty($record)) {
            return $record['num'];
        }
        return 0;
    }

    /**
     * 取商品到购物车
     * @param unknown $memberId
     * @param unknown $clientIdcard
     * @param unknown $skuId
     * @param unknown $buyPoductNum
     * @param unknown $warehouseType
     * @param unknown $supplierId
     */
    public function takeProductToCart($member_id,$shop_id,$skuid,$warehouseType,$supplierId,$buyPoductNum,$existsNum)
    {
        // 获取sku商品信息
        $model = new ProductSkuModel();
        $skuInfo = $model->getInfoById($skuid);
        if (empty($skuInfo)) { //商品不存在
            return ['code'=>300,'msg'=>'商品不存在'];
        }
        // 获取已存在于购物车中的信息
        $where = "product_id=$skuid and status>0";
        if ($member_id > 0) {
            $where .= " and member_id = $member_id";
        }
       /* if($shop_id){
            $where .= " and ms_id=$shop_id";
        }

        if ($supplierId !== null) {
            $where .= " and supplier_id = $supplierId";
        }
        if ($warehouseType !== null) {
            $where .= " and warehouse_type=$warehouseType";
        }*/
        if($existsNum!=0){
            $res = $this->where($where)->save(['num'=>$buyPoductNum]);
        }else{
            $res = $this->addNewData($member_id,$shop_id, $skuInfo, $buyPoductNum, $warehouseType, $supplierId);
        }
        $model = new ProductCartModel();
        $count = $model->where("status>0 and active_id!=3 and member_id=$member_id")->sum('num');
        if($res){
            return ['num' => $count,'code' => 200,'msg'=>'购物车更新成功'.$supplierId];
        }else{
            return ['msg' => '购物车更新失败','code' => 300];
        }
    }
    /**
     * 添加一条新数据
     * @param unknown $memberId
     * @param unknown $clientIdcard
     * @param unknown $skuInfo
     * @param unknown $buyPoductNum
     */
    public function addNewData($memberId,$shop_id, $skuInfo, $buyPoductNum, $warehouseType, $supplierId)
    {
        $data = [
            'member_id'  => $memberId,
            'ms_id'      => $shop_id,
            'product_id' => $skuInfo['id'],
            'stock_shop' => $skuInfo['stock_shop'],
            'num'        => $buyPoductNum,
            'warehouse_type' => $warehouseType,
            'supplier_id' => $supplierId,
            'active_id' => 0,
            'is_selected' => 1,
            'status'      => 1,
        ];

        return $this->add($data);
    }

    /**
     * 获取购物车数据
     */
    public function cart_list($member_id){
        $list = $this->alias('c')->join("left join haiou_product_sku as pa on pa.id=c.product_id")->where("c.status>0 and c.active_id!=3 and c.member_id=$member_id")->field("c.num,pa.pname,pa.ms_price,pa.pic,c.stock_shop,c.id,pa.id as skuid,pa.ms_stock_supplierid,pa.ms_entrepot_supplierid,pa.ms_direct_supplierid")->select();
        if($list){
            $total_money = 0;
            $model = new ProductSkuModel();
            $product_id = [];
            foreach($list as $k=>$v){
                $ways = [];
                $way = $model->getShipmentsWay($v['skuid'], 1, $v['ms_stock_supplierid']);
                if (!empty($way)) {
                    $ways[] = $way;
                }

                //是否存在于保税仓库
                $warehouseType = 1;
                $way = $model->getShipmentsWay($v['skuid'], 2, $v['ms_entrepot_supplierid']);
                if (!empty($way)) {
                    $ways[] = $way;
                }

                //是否存在于直邮仓
                $warehouseType = 1;
                $way = $model->getShipmentsWay($v['skuid'], 3, $v['ms_direct_supplierid']);
                if (!empty($way)) {
                    $ways[] = $way;
                }
                $list[$k]['stock'] = $ways[0]['stock'];
                $total_money += ($v['ms_price']*$v['num']);
                $pic = explode(',',$v['pic']);
                $list[$k]['pic'] = $pic[0];
            }
            foreach($list as $v){
                $lists[$v['stock_shop']][] = $v;
            }
            if(empty($lists)){
                $lists = [];
            }
            if($lists){
                foreach($lists as $k=>$v){
                    $money = 0;
                    foreach($v as $s){
                        $money += $s['ms_price']*$s['num'];
                    }
                    $model = new StockShopsModel();
                    $info = $model->getInfoById($k);
                    $lists[$k]['title'] = $info['show_title'];
                    $lists[$k]['money'] = $money;
                    $model = new LogisticsTempConModel();
                    $info1 = $model->getRow($info['logisticsid']);
                    $lists[$k]['free'] = intval($info1['free']);
                    $lists[$k]['logisticsId'] = $info['logisticsid'];

                }
            }
        }
        $count = $this->where("status>0 and active_id!=3 and member_id=$member_id")->sum('num');
        $res['count'] = $count;
        $res['list']  = $lists;
        $res['product_id'] = json_encode($product_id);
        $res['total_money']  = $total_money;
        return $res;
    }


    /**
     * 根据商品id查询购物车商品
     */
    public function cartSkuList($member_id,$skuids){
        $model = new MemberModel();
        $member_info = $model->where("userid=$member_id")->find();
        if(empty($member_info['mobile'])){
            return ['code'=>300,'msg'=>'你还没有绑定手机号'];
        }
        $list = $this->alias('c')->join("left join haiou_product_sku as pa on pa.id=c.product_id")->where("c.status>0 and c.active_id!=3 and c.member_id=$member_id")->field("c.num,pa.pname,pa.ms_price,pa.pic,c.stock_shop,c.id,pa.id as skuid,pa.ms_stock_supplierid,pa.ms_entrepot_supplierid,pa.ms_direct_supplierid,pa.spec,pa.catid,pa.pic,pa.ms_discount,pa.ms_taxation")->select();
        if($list){
            $total_money = 0;
            $model = new ProductSkuModel();
            foreach($list as $k=>$v){
                $pic = explode(',',$v['pic']);
                $list[$k]['pic'] = $pic;
                $ways = [];
                $way = $model->getShipmentsWay($v['skuid'], 1, $v['ms_stock_supplierid']);
                if (!empty($way)) {
                    $ways[] = $way;
                }

                //是否存在于保税仓库
                $warehouseType = 1;
                $way = $model->getShipmentsWay($v['skuid'], 2, $v['ms_entrepot_supplierid']);
                if (!empty($way)) {
                    $ways[] = $way;
                }

                //是否存在于直邮仓
                $warehouseType = 1;
                $way = $model->getShipmentsWay($v['skuid'], 3, $v['ms_direct_supplierid']);
                if (!empty($way)) {
                    $ways[] = $way;
                }
                $list[$k]['stock'] = $ways[0]['stock'];
                $total_money += $v['ms_price'];
                $pic = explode(',',$v['pic']);
                $list[$k]['pic'] = $pic[0];
                $list[$k]['warehouseType'] = $ways[0]['warehouseType'];
            }
            foreach($list as $v){
                $lists[$v['stock_shop']][] = $v;
            }
            if(empty($lists)){
                $lists = [];
            }
            if($lists){
                foreach($lists as $k=>$v){
                    $money = 0;
                    foreach($v as $s){
                        $money += $s['ms_price'];
                    }
                    $model = new StockShopsModel();
                    $info = $model->getInfoById($k);
                    $lists[$k]['title'] = $info['show_title'];
                    $lists[$k]['money'] = $money;
                    $model = new LogisticsTempConModel();
                    $info1 = $model->getRow($info['logisticsid']);
                    $lists[$k]['free'] = intval($info1['free']);
                    $lists[$k]['logisticsId'] = $info['logisticsid'];
                }
            }
        }else{
            $lists = [];
        }
        return $lists;
    }
}